package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.landeb.shop.R;
import com.landeb.shop.huo.GlideCircleTransform;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.bean.BeanUserData;
import com.landeb.shop.huo.httpRequest.EditUserProfileRequest;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;

import me.shaohui.advancedluban.Luban;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ProfileEditActivity extends TakePhotoActivity implements View.OnClickListener {

    private Button btnMore;
    private LinearLayout btnBack;
    private LinearLayout mHeadPicLayout, mAccountLayout, mNameLayout, mSexLayout, mAddressLayout, mChangePasswordLayout;
    private ImageView mHeadPic;
    private TextView mTvAccount, mTvName, mTvSex;

    private EditText dialogTvName;
    private String mSex;
    private String mName;
    private int mHeadPicMode;
    public static final int GET_HEAD_PIC_FROM_CAM = 0;
    public static final int GET_HEAD_PIC_FROM_SD = 1;


    private String mUrl;
    private Retrofit mRetrofit;
    private EditUserProfileRequest mRequest;
    private boolean isUpdatingName = false;
    private boolean isUpdatingSex = false;
    private boolean isUpdatingHeadPic = false;

    public static void toAct(Context context) {
        Intent intent = new Intent(context, ProfileEditActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_edit);

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(EditUserProfileRequest.class);


        initView();
        initData();
        initEvent();

        refresh();

    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnMore.setOnClickListener(this);
        mHeadPicLayout.setOnClickListener(this);
        mAccountLayout.setOnClickListener(this);
        mNameLayout.setOnClickListener(this);
        mSexLayout.setOnClickListener(this);
        mAddressLayout.setOnClickListener(this);
        mChangePasswordLayout.setOnClickListener(this);

    }

    private void initData() {

    }

    private void initView() {

        btnBack = (LinearLayout) findViewById(R.id.act_profile_edit_btn_back);
        btnMore = (Button) findViewById(R.id.act_profile_edit_btn_more);

        mHeadPicLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_head_pic);
        mAccountLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_account);
        mNameLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_name);
        mSexLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_sex);
        mAddressLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_address);
        mChangePasswordLayout = (LinearLayout) findViewById(R.id.act_profile_edit_ll_resetPassword);

        mHeadPic = (ImageView) findViewById(R.id.act_profile_edit_iv_head);
        mTvAccount = (TextView) findViewById(R.id.act_profile_edit_tv_account);
        mTvName = (TextView) findViewById(R.id.act_profile_edit_tv_name);
        mTvSex = (TextView) findViewById(R.id.act_profile_edit_tv_sex);

        if (MyApplication.mUserInfo != null) {

            BeanUserData.DataBean mUserInfo = MyApplication.mUserInfo;

            mTvName.setText(mUserInfo.getNickname());
            mTvAccount.setText(mUserInfo.getUsername());

            String sex = null;

            if (mUserInfo.getSex().equals("1")) {
                sex = "女";
            } else {
                sex = "男";
            }

            mTvSex.setText(sex);

            String headPicUrl = MyApplication.BASE_URL+"Public/user_head/uid/" + mUserInfo.getId();
//            Glide.with(this).load(headPicUrl)
////                    .transform(new GlideCircleTransform(this))
//                    .into(mHeadPic);
        }

    }

    @Override
    public void onClick(View view)  {

        switch (view.getId()) {

            case R.id.act_profile_edit_btn_back:
                // TODO: 2016/11/3 返回键
                onBackPressed();
                break;
            case R.id.act_profile_edit_btn_more:
                // TODO: 2016/11/3 不知道干嘛的剑
                break;
            case R.id.act_profile_edit_ll_head_pic:

                final String[] picChoose = {"拍照", "从相册选择"};
                android.support.v7.app.AlertDialog.Builder headPicBuilder = new android.support.v7.app.AlertDialog.Builder(this);
                headPicBuilder.setSingleChoiceItems(picChoose, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // TODO: 2016/11/7 获取头像逻辑

                        if (picChoose[i].equals("拍照")) {
                            mHeadPicMode = GET_HEAD_PIC_FROM_CAM;
                        } else {
                            mHeadPicMode = GET_HEAD_PIC_FROM_SD;
                        }

                    }
                })
                        .setTitle("设置头像")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // TODO: 2016/11/3 获取头像

                                TakePhoto takePhoto = getTakePhoto();

                                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                                Uri imageUri = Uri.fromFile(file);

                                CropOptions.Builder cropBuilder = new CropOptions.Builder();
                                cropBuilder.setOutputX(800)
                                        .setOutputY(800)
                                        .setWithOwnCrop(true);

                                LubanOptions config = new LubanOptions.Builder()
                                        .setGear(Luban.CUSTOM_GEAR)
                                        .setMaxHeight(800)
                                        .setMaxWidth(800)
                                        .setMaxSize(1024 * 1024)
                                        .create();
                                boolean showProgressBar = true;
                                CompressConfig compressConfig = CompressConfig.ofLuban(config);
                                takePhoto.onEnableCompress(compressConfig, showProgressBar);

                                if (mHeadPicMode == GET_HEAD_PIC_FROM_CAM) {
                                    takePhoto.onPickFromCaptureWithCrop(imageUri, cropBuilder.create());
                                } else {
                                    takePhoto.onPickFromDocumentsWithCrop(imageUri, cropBuilder.create());
//                                    takePhoto.onPickFromGalleryWithCrop(imageUri,cropBuilder.create());
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .setCancelable(false)
                        .show();


                // TODO: 2016/11/3 点击头像栏
                break;
            case R.id.act_profile_edit_ll_account:
                // TODO: 2016/11/3 点击用户名栏
                Toast.makeText(this, "用户名不能改", Toast.LENGTH_SHORT).show();
                break;
            case R.id.act_profile_edit_ll_name:
                // TODO: 2016/11/3 点击昵称lan

                dialogTvName = new EditText(ProfileEditActivity.this);

                android.support.v7.app.AlertDialog.Builder nameBuilder = new android.support.v7.app.AlertDialog.Builder(this);
                nameBuilder.setTitle("请输入昵称")
                        .setView(dialogTvName)
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                if (TextUtils.isEmpty(dialogTvName.getText().toString().trim())) {
                                    Toast.makeText(ProfileEditActivity.this, "请输入昵称", Toast.LENGTH_SHORT).show();
                                } else {
                                    mName = dialogTvName.getText().toString();
                                    // TODO: 2016/11/3 修改昵称逻辑
                                    updateName();

                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();

                break;
            case R.id.act_profile_edit_ll_sex:
                // TODO: 2016/11/3 点击性别栏 、
                final String[] sexChoose = {"男", "女"};
                android.support.v7.app.AlertDialog.Builder sexBuilder = new android.support.v7.app.AlertDialog.Builder(this);

                sexBuilder.setTitle("选择您的性别")
                        .setSingleChoiceItems(sexChoose, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mSex = sexChoose[i];
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                updateSex();

                            }
                        })
                        .setNegativeButton("取消", null)
                        .setCancelable(false)
                        .show();
                break;
            case R.id.act_profile_edit_ll_address:
                // TODO: 2016/11/3 点击地址栏
                break;

            case R.id.act_profile_edit_ll_resetPassword:
                // TODO: 2016/11/16 修改密码
                PasswordChangeActivity.toAct(this);
                break;

        }

    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        // TODO: 2016/11/7 图片剪切成功回调  完成头像上传和本地头像更新

//        Glide.with(this).load(new File(result.getImage().getPath())).transform(new GlideCircleTransform(this)).into(mHeadPic);
        ArrayList<TImage> images = result.getImages();

        File imgFile = new File(images.get(0).getPath());

        updateHeadPic(imgFile);

//        Glide.with(this).load(imgFile).transform(new GlideCircleTransform(this)).into(mHeadPic);
        Log.e("takeSuccess:xxxxxxxxxx ", images.size() + "");
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("takeCancel: ", "takeFail");
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        Log.e("takeCancel: ", "takeCancel");
    }

    private void updateName() {

        if (!isUpdatingName) {
            isUpdatingName = true;

            mRequest.updataNickName(mName)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanStatusInfo>() {
                        @Override
                        public void onCompleted() {
                            isUpdatingName = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            isUpdatingName = false;
                        }

                        @Override
                        public void onNext(BeanStatusInfo beanStatusInfo) {

                            if (beanStatusInfo.getStatus() == 1) {
                                mTvName.setText(mName);
                            } else {
                                Toast.makeText(ProfileEditActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
        }


    }

    private void updateSex() {

        if (!isUpdatingSex && mSex != null) {
            isUpdatingSex = true;

            String updateSex = null;

            if (mSex.equals("男")) {
                updateSex = "2";
            } else if (mSex.equals("女")) {
                updateSex = "1";
            }

            mRequest.updataSex(updateSex)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanStatusInfo>() {
                        @Override
                        public void onCompleted() {
                            isUpdatingSex = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            isUpdatingSex = false;
                        }

                        @Override
                        public void onNext(BeanStatusInfo beanStatusInfo) {

                            if (beanStatusInfo.getStatus() == 1) {
                                mTvSex.setText(mSex);
                            } else {
                                Toast.makeText(ProfileEditActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
        }


    }

    private void updateHeadPic(final File file) {

        if (!isUpdatingHeadPic) {

            isUpdatingHeadPic = true;

            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

            mRequest.updateHeadPic(requestBody)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<BeanStatusInfo>() {
                        @Override
                        public void onCompleted() {
                            isUpdatingHeadPic = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            isUpdatingHeadPic = false;

                            Log.e("updatepicXXXXXonError: ", e.getMessage().toString());
                        }

                        @Override
                        public void onNext(BeanStatusInfo beanStatusInfo) {

                            if (beanStatusInfo.getStatus() == 0) {
                                Toast.makeText(ProfileEditActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                            } else if (beanStatusInfo.getStatus() == 1) {

                                if (MyApplication.mUserInfo == null) {
                                    return;
                                }
                                BeanUserData.DataBean mUserInfo = MyApplication.mUserInfo;
//                                String headPicUrl = "http://shop.xuji.cm:8080/index.php/Api/Public/user_head/uid/" + mUserInfo.getId();
                                String headPicUrl = MyApplication.BASE_URL+"Public/user_head/uid/" + mUserInfo.getId();
                                Glide.with(ProfileEditActivity.this).load(headPicUrl).transform(new GlideCircleTransform(ProfileEditActivity.this)).into(mHeadPic);

                            }

                        }
                    });

        }


    }

    private void refresh() {

        if (MyApplication.mUserInfo == null) {

            String headPicUrl = MyApplication.BASE_URL+"Public/user_head/uid/" + "0";
            Glide.with(this).load(headPicUrl).transform(new GlideCircleTransform(this)).into(mHeadPic);

            return;
        }

        BeanUserData.DataBean mUserInfo = MyApplication.mUserInfo;

        mTvName.setText(mUserInfo.getNickname());
        mTvAccount.setText(mUserInfo.getUsername());

        String sex = null;

        if (mUserInfo.getSex().equals("1")) {
            sex = "女";
        } else {
            sex = "男";
        }

        mTvSex.setText(sex);

        String headPicUrl = MyApplication.BASE_URL+"Public/user_head/uid/" + mUserInfo.getId();
        Glide.with(this).load(headPicUrl).transform(new GlideCircleTransform(this)).into(mHeadPic);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (MyApplication.mUserInfo == null) {
            return;
        }

        Gson gson = new Gson();
        String userData = gson.toJson(MyApplication.mUserInfo);

        SharedPreferences mPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("userData", userData);
        editor.commit();

    }
}
